



import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import xmlParser.ColFieldType;
import xmlParser.FieldInteger;
import xmlParser.FieldString;
import xmlParser.TypedColField;
import xmlParser.TypedRecord;
import xmlParser.TypedTable;

public class PopulateDB {

	//All the fields in the table
	ArrayList<ColFieldType> fieldTypes = new ArrayList<ColFieldType>();
	
	//Subset of fields which user specifies for dumping into DB.
	TypedTable typedTable = new TypedTable();
	
	public PopulateDB() {
	}
	
	public void initialize(String tableName, String []fTypeName, ArrayList<String> subsetFieldNames,
				String fileName, String delim, String odbc)
	{
		int j = 0;
		while(fTypeName[j] != null)
		   {
			StringTokenizer Tok = new StringTokenizer(fTypeName[j]," ");
			int n = 0;
			String name = null, type = null;
			while (Tok.hasMoreElements())
			{
				//Getting the field name
				if(n == 0)
				{
					name = (String)Tok.nextElement();
				}
				
				//Getting the field type
				else if(n == 1)
				{
					type = (String)Tok.nextElement();
				}

				
				n++;
			}
			//Adding the field type information to the typedTable
			ColFieldType colFieldType = new ColFieldType(name,type);
			this.fieldTypes.add(colFieldType);
			j++;
		   }
		
		//Populating the subset of fields
		for(String selectedField : subsetFieldNames)
		{
			StringTokenizer Tok = new StringTokenizer(selectedField," ");
			int n = 0;
			String name = null, type = null;
			while (Tok.hasMoreElements())
			{
				//Getting the field name
				if(n == 0)
				{
					name = (String)Tok.nextElement();
				}

				//Getting the field type
				else if(n == 1)
				{
					type = (String)Tok.nextElement();
				}
				n++;
			}
			//Adding the field type information to the typedTable
			ColFieldType colFieldType = new ColFieldType(name,type);
			typedTable.fieldType.add(colFieldType);
		}
		
		//Insert the subset fields
		System.out.println("debug");
		DataInputStream dis = null;
		String record = null;
		int recCount = 0;
		
		try
		{

			File f = new File(fileName);// file name  
			FileInputStream fis = new FileInputStream(f);
			BufferedInputStream bis = new BufferedInputStream(fis);
			dis = new DataInputStream(bis);
			
			while ((record = dis.readLine()) != null)
			{
				TypedRecord typedRecord = new TypedRecord();
				
				//modify the delimiter based on the user input
				StringTokenizer Tok = new StringTokenizer(record,delim);
				int n = 0;
				while (Tok.hasMoreElements())
				{
					String fieldName = this.fieldTypes.get(n).name;
					
					if(this.typedTable.fieldExists(fieldName))
					{
						ColFieldType colFieldType3 = this.typedTable.colFieldType(fieldName);
						//TypedColField
						//note: the sqlTypeInt returns a flag based off the type, i.e.
						//VARCHAR returns flag 12.  We are only using these two for now.
						switch(sqlTypeInt(colFieldType3.type))
						{
						case 12:/*VARCHAR*/
							FieldString fieldString = new FieldString(colFieldType3.name,
									"VARCHAR", (String)Tok.nextElement());
							typedRecord.addField(fieldString);
							break;
						case 4:/*INTEGER*/
							FieldInteger fieldInteger = new FieldInteger(colFieldType3.name,
									"INTEGER", Integer.parseInt((String) Tok.nextElement()));
							typedRecord.addField(fieldInteger);
							break;
							//TODO! Have to code for other types
						default: 
							Tok.nextElement();
						}
						n++;
						continue;
					}
					n++;
					Tok.nextElement();
				}
				this.typedTable.addRecord(typedRecord);
			}
			System.out.println("debug");
			

			for(TypedRecord typedRecord : this.typedTable.typedRecords)
			{
				//Adding the rows in the table
				String insertStr = "INSERT INTO " + tableName + " (";
				String valueStr = "(";
				for(TypedColField typedColField : typedRecord.getTypedColFields())
				{
					insertStr += typedColField.getName();
					insertStr += ",";
					valueStr += "'";
					valueStr += typedColField.getValue();
					valueStr += "'";
					valueStr += ",";
				}
				valueStr = valueStr.substring(0, valueStr.length()-1);
				valueStr += ")";
				insertStr = insertStr.substring(0, insertStr.length()-1);
				insertStr += ") ";
				insertStr += "VALUES ";
				insertStr += valueStr + ";";
				
				//update db
				RunDB runDB = new RunDB();
				try {
					runDB.loadDriver();
					//need to pass in the name of ODBC here.

					runDB.makeConnection(odbc);
					runDB.buildStatement();
					
					boolean setXML = true;
			        //grab the sql entry from the sql entry table.
			        runDB.executeQuery(insertStr,setXML);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
		}

		catch (IOException e)
		{
			// catch io errors from FileInputStream or readLine()
			System.out.println("Uh oh, got an IOException error!" + e.getMessage());

		}
	}
	
	/**
	 * Only for testing...no need to go through this.
	 * @param args
	 */
	
	private static Integer sqlTypeInt(String type)
	   {
		   if(type.equals("VARCHAR"))
			   return 12;
		   else if(type.equals("INTEGER") || type.equals("INT"))
			   return 4;
		   return -1;
	   }
}
